package cm.tl.pms.util.fileParser.excel;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FixedWidthColumnStyleStrategy extends AbstractColumnWidthStyleStrategy {

    private static final int FIXED_COLUMN_WIDTH = 20; // 固定列宽
    private final Map<Integer, Map<Integer, Integer>> cache = MapUtils.newHashMapWithExpectedSize(8);

    public FixedWidthColumnStyleStrategy() {
    }

    @Override
    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
        if (needSetWidth) {
            Map<Integer, Integer> maxColumnWidthMap = this.cache.get(writeSheetHolder.getSheetNo());
            if (maxColumnWidthMap == null) {
                maxColumnWidthMap = new HashMap<>(16);
                this.cache.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);
            }

            // 固定列宽
            Integer fixedColumnWidth = FIXED_COLUMN_WIDTH;  // 设置为固定宽度
            Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());

            // 如果当前列宽小于固定宽度，就更新为固定宽度
            if (maxColumnWidth == null || fixedColumnWidth > maxColumnWidth) {
                maxColumnWidthMap.put(cell.getColumnIndex(), fixedColumnWidth);
                writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), fixedColumnWidth * 256); // 乘以256是因为Excel列宽的单位
            }
        }
    }
}
